package com.gxitsky.async.design.controller;

import com.gxitsky.async.design.config.ClusterNode;
import com.gxitsky.async.design.config.PropertiesConfig;
import com.gxitsky.utils.JSON;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @author gxing
 * @desc TODO
 * @date 2022/7/25
 */
@Controller
public class HelloController {

    @Autowired
    protected PropertiesConfig propertiesConfig;
    @Autowired
    private ClusterNode clusterNode;

    @ResponseBody
    @RequestMapping("/properties")
    public void properties() throws IOException {
        System.out.println("osName:" + propertiesConfig.getOsName());
        System.out.println("intRandomNumber:" + propertiesConfig.getIntRandomNumber());
        System.out.println("doubleRandomNumber:" + propertiesConfig.getDoubleRandomNumber());
        System.out.println("beanValue:" + propertiesConfig.getBeanValue());
        System.out.println("demoFile:" + IOUtils.toString(propertiesConfig.getDemoFile().getInputStream(), StandardCharsets.UTF_8));
        System.out.println("booleanValue:" + propertiesConfig.isBooleanValue());
        System.out.println("intValue:" + propertiesConfig.getIntValue());
        System.out.println("cluster node:" + Arrays.toString(clusterNode.getNode().toArray()));
        System.out.println("some name:" + Arrays.toString(propertiesConfig.getSomeName().toArray()));
        System.out.println("some hobby:" + Arrays.toString(propertiesConfig.getHobby().toArray()));
        System.out.println("appid map:" + JSON.toJsonString(propertiesConfig.getMaps()));
        System.out.println("map with default:" + JSON.toJsonString(propertiesConfig.getMapWithDefault()));
    }


    @RequestMapping("/hello")
    public void detail(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", 100L);
            map.put("body", "Hello World");
            PrintWriter writer = servletResponse.getWriter();
            servletResponse.setContentType("application/json;charset=UTF-8");
            writer.write(JSON.toJsonString(map));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
